package com.yld.car.market;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.yld.car.common.CompressImageUtils;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.ImageUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.EditCarInfo;

public class PublishCarPickPhotoActivity extends BaseActivity implements
		OnClickListener {

	// 图片编辑状态
	private boolean isEditor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.publish_car_pick_photo);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView) findViewById(R.id.title)).setText("选择图片");

		Button localButton = (Button) findViewById(R.id.rightButton);
		localButton.setText("保存");
		// showBackButton();
		progressBackButton();
		Intent intent = this.getIntent();
		if (intent != null) {
			isEditor = intent.getBooleanExtra("isEditor", false);
		}

		// for (String string : tests) {
		// System.out.println("string==" + string);
		// }
		// System.out.println("img====" + e.getImg());
		// aq.id(imageView).image(downloadUrl);
		imgButton1 = (ImageButton) findViewById(R.id.imageButton1);
		imgButton1.setOnClickListener(this);
		// utils = NetworkProgressUtils.getInstance();
		imgButton2 = (ImageButton) findViewById(R.id.imageButton2);
		imgButton2.setOnClickListener(this);

		imgButton3 = (ImageButton) findViewById(R.id.imageButton3);
		imgButton3.setOnClickListener(this);

		imgButton4 = (ImageButton) findViewById(R.id.imageButton4);
		imgButton4.setOnClickListener(this);

		System.out.println("isEditor==" + isEditor);
		if (isEditor) {

			AQuery aq = new AQuery(this);
			EditCarInfo e = mApp.getmEditCarInfo();
			String img = e.getImg();
			String[] tests = img.split(";");
			int size = tests.length;
			HashMap<String, String> all = mApp.getAllImgPaths();
			if (size == 1) {
				aq.id(imgButton1).image(tests[0]);
				all.put("1", tests[0]);
			} else if (size == 2) {
				aq.id(imgButton1).image(tests[0]);
				aq.id(imgButton2).image(tests[1]);
				all.put("1", tests[0]);
				all.put("2", tests[1]);
			} else if (size == 3) {
				aq.id(imgButton1).image(tests[0]);
				aq.id(imgButton2).image(tests[1]);
				aq.id(imgButton3).image(tests[2]);
				all.put("1", tests[0]);
				all.put("2", tests[1]);
				all.put("3", tests[2]);
			} else if (size == 4) {
				aq.id(imgButton1).image(tests[0]);
				aq.id(imgButton2).image(tests[1]);
				aq.id(imgButton3).image(tests[2]);
				aq.id(imgButton4).image(tests[3]);
				all.put("1", tests[0]);
				all.put("2", tests[1]);
				all.put("3", tests[2]);
				all.put("4", tests[3]);
			}
		} else {
			final HashMap<String, String> allImgs = mApp.getAllImgPaths();
			// System.out.println(allImgs+"%%%%");
			if (allImgs != null && allImgs.size() != 0) {
				new Thread(new Runnable() {

					@Override
					public void run() {

						Set s = allImgs.entrySet();
						Iterator i = s.iterator();
						while (i.hasNext()) {
							Entry e = (Entry) i.next();

							String fileName = e.getValue().toString();
							try {

								Bitmap bitmap = ImageUtils
										.convertBitmapByPathName(fileName);
								Message msg = mHander.obtainMessage();
								msg.arg1 = Integer.parseInt(e.getKey()
										.toString());
								msg.obj = bitmap;
								mHander.sendMessage(msg);
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}

					}
				}).start();

			}
		}

		localButton.setVisibility(View.VISIBLE);
		localButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramView) {

				HashMap<String, String> allPaths = mApp.getAllImgPaths();
				if (allPaths != null && allPaths.size() == 4) {
					mApp.setImgSave(true);
					mApp.setDefault(false);
					finish();
				} else {
					Toast.makeText(PublishCarPickPhotoActivity.this,
							"亲，要上传爱车的图片必须是四张哟^,^", Toast.LENGTH_SHORT).show();

				}

			}
		});
	}

	Handler mHander = new Handler() {

		public void handleMessage(android.os.Message msg) {

			int arg = msg.arg1;
			Bitmap bitmap = (Bitmap) msg.obj;
			if (arg == 1) {
				imgButton1.setImageBitmap(bitmap);
			} else if (arg == 2) {
				imgButton2.setImageBitmap(bitmap);
			} else if (arg == 3) {
				imgButton3.setImageBitmap(bitmap);
			} else if (arg == 4) {
				imgButton4.setImageBitmap(bitmap);
			}
		}
	};

	/**
	 * 定义统一的返回按键设置功能
	 */
	private void progressBackButton() {
		Button localButton = (Button) findViewById(R.id.leftButton);
		localButton.setVisibility(View.VISIBLE);
		localButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramView) {

				if (!mApp.isImgSave()) {
					mApp.getAllImgPaths().clear();
					// 直接返回用系统默认的图片
					mApp.setDefault(true);
				}
				// if (!mApp.isImgSave()) {
				// // 删除上传在服务器端的图片
				// new Thread(new Runnable() {
				//
				// @Override
				// public void run() {
				//
				// // string fileName
				// ArrayList<String> all = mApp.getAllImgNames();
				// for (int i = 0; i < all.size(); i++) {
				//
				// String fileName = all.get(i);
				// HashMap<String, Object> allParams = new HashMap<String,
				// Object>();
				// allParams.put("fileName", fileName);
				// Object o = utils
				// .uploadImage(
				// ConstantUtils.NAME_SPACE,
				// ConstantUtils.ALL_METHROD_NAME
				// .get(12),
				// ConstantUtils.NAME_SPACE
				// + ConstantUtils.ALL_METHROD_NAME
				// .get(12),
				// ConstantUtils.GET_DELETE_FILE_URL,
				// allParams);
				// System.out.println(o);
				// }
				//
				// }
				// }).start();
				// }
				finish();
			}
		});
	}

	// private NetworkProgressUtils utils;
	private ImageButton imgButton1;
	private ImageButton imgButton2;
	private ImageButton imgButton3;
	private ImageButton imgButton4;

	// private static String cameraImageBasePath = "/ichehang/cache/pic/";
	private String cameraFileName = "car_add_tmp_pic";

	private void photoDo(int paramInt) {
		if (paramInt == 0) {
			if (Environment.getExternalStorageState().equals("mounted"))
				try {
					File localFile = new File(IMG_CACHE_PATH);
					if (!localFile.exists())
						localFile.mkdirs();
					Intent localIntent = new Intent(
							"android.media.action.IMAGE_CAPTURE");
					localIntent.putExtra("output",
							Uri.fromFile(new File(localFile, cameraFileName)));
					startActivityForResult(localIntent, 1);
					return;
				} catch (ActivityNotFoundException localActivityNotFoundException) {
					Toast.makeText(this, "没有找到储存目录", 1).show();
					return;
				}
			Toast.makeText(this, "请插入SD Card", Toast.LENGTH_SHORT).show();
			return;
		}
		startActivityForResult(new Intent("android.intent.action.PICK",
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 2);
	}

	private void selectPhotoWay() {
		String[] arrayOfString = "拍照,从相册中选择".split(",");
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
		localBuilder.setItems(arrayOfString,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int which) {
						photoDo(which);
					}
				});
		localBuilder.setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int paramInt) {
					}
				});
		localBuilder.create().show();
	}

	// private void setImageView(Context paramContext, ImageView paramImageView,
	// String paramString) {
	//
	// }

	private int uploadImgIndex;

	@Override
	public void onClick(View v) {

		EditCarInfo editCarInfo = mApp.getmEditCarInfo();
		if (editCarInfo != null && !editCarInfo.isIshead().equals("0")) {

			Toast.makeText(this, "车源图片由系统提供，不能编辑", Toast.LENGTH_SHORT).show();
			return ;
		}
		int id = v.getId();
		switch (id) {
		case R.id.imageButton1:
			uploadImgIndex = 1;
			break;

		case R.id.imageButton2:
			uploadImgIndex = 2;
			break;

		case R.id.imageButton3:
			uploadImgIndex = 3;
			break;

		case R.id.imageButton4:
			uploadImgIndex = 4;
			break;
		}

		selectPhotoWay();
	}

	public static String IMG_CACHE_PATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/ichehang/cache/pic/";

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		Uri uri = null;
		if (requestCode == 1) {

			File localFile = new File(IMG_CACHE_PATH);
			uri = Uri.fromFile(new File(localFile, cameraFileName));

		} else if (requestCode == 2) {
			// System.out.println(data);
			if (data == null) {
				return;
			}
			uri = data.getData();

		}

		if (uri == null) {

			return;
		}

		String pathName = "";
		if (uri.toString().indexOf("content://") >= 0) {

			ContentResolver cr = getContentResolver();
			Cursor c = cr.query(uri, null, null, null, null);
			// System.out.println(c.getCount());
			c.moveToFirst();
			pathName = c.getString(c
					.getColumnIndex(MediaStore.Images.Media.DATA));

		} else {
			pathName = IMG_CACHE_PATH + cameraFileName;
			// System.out.println("pathName==" + pathName);
		}
		// mApp.getAllImgPaths().put("" + uploadImgIndex, pathName);
		ImageButton img = null;
		if (uploadImgIndex == 1) {
			img = this.imgButton1;
		} else if (uploadImgIndex == 2) {
			img = this.imgButton2;
		} else if (uploadImgIndex == 3) {
			img = this.imgButton3;
		} else if (uploadImgIndex == 4) {
			img = this.imgButton4;
		}
		new UploadImageTask(img, uploadImgIndex + "").execute(pathName);

		// new UploadImageTask().execute(pathName);
	}

	/**
	 * 上传图片文件的任务
	 * 
	 * @author apple
	 * 
	 */
	class UploadImageTask extends AsyncTask<String, String, Boolean> {

		public UploadImageTask(ImageButton img, String imgKey) {
			this.img = img;
			this.imgKey = imgKey;
		}

		private String imgKey;
		private ImageButton img;

		@Override
		protected Boolean doInBackground(String... params) {
			try {

				String pathName = params[0];
				String destPath = COMPRESS_IMG_ROOT;
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsS");
				String imgName = sdf.format(new Date());
				String destName = destPath + imgName + ".jpg";
				boolean b = CompressImageUtils.writeImageToFile(pathName,
						destName);
				mApp.getAllImgPaths().put(imgKey, destName);
				return Boolean.valueOf(b);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {

			showLoading("正在上传图片，请等待！");
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			hideLoading();
			if (result != null && result.booleanValue()) {
				String str = mApp.getAllImgPaths().get(imgKey);
				Bitmap bitmap = ImageUtils.convertBitmapByPathName(str);

				img.setImageBitmap(bitmap);

			}

			super.onPostExecute(result);
		}

	}

	public static final String COMPRESS_IMG_ROOT = IMG_CACHE_PATH;
}
